package com.example.train_operate.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class CommunityUtil {

    // 生成盐值
    public static byte[] generateSalt() {
        byte[] salt = new byte[16];
        SecureRandom random = new SecureRandom();
        random.nextBytes(salt);
        return salt;
    }

    // MD5加盐加密
    public static String encryptWithSalt(String password, byte[] salt) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(salt);
            byte[] hashedPassword = md.digest(password.getBytes());

            // 将盐和哈希值合并存储
            byte[] combined = new byte[salt.length + hashedPassword.length];
            System.arraycopy(salt, 0, combined, 0, salt.length);
            System.arraycopy(hashedPassword, 0, combined, salt.length, hashedPassword.length);

            return Base64.getEncoder().encodeToString(combined);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not available", e);
        }
    }

    // 验证密码
    public static boolean verifyPassword(String password, String storedHash) {
        // 解码存储的哈希值
        byte[] combined = Base64.getDecoder().decode(storedHash);

        // 提取盐值
        byte[] salt = new byte[16];
        System.arraycopy(combined, 0, salt, 0, salt.length);

        // 计算输入密码的哈希值
        String testHash = encryptWithSalt(password, salt);

        // 比较两个哈希值
        return testHash.equals(storedHash);
    }
}